package com.junsi.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.junsi.bean.Client;
import com.junsi.bean.Company;
import com.junsi.bean.Department;
import com.junsi.bean.Newrecord;
import com.junsi.bean.Rank;
import com.junsi.bean.Record;
import com.junsi.bean.Staff;

import com.junsi.service.ClientService;
import com.junsi.service.CompanySerivce;
import com.junsi.service.DepartmentSerivce;
import com.junsi.service.NewrecordService;
import com.junsi.service.RankService;
import com.junsi.service.RecordService;
import com.junsi.service.StaffSerivce;

import com.junsi.util.DaoChuExcel;
import com.junsi.util.DaoRuExcel;
import com.junsi.util.DownFile;
import com.junsi.util.DownlaodExcel;
import com.junsi.util.FileUtil;
import com.junsi.util.InteractiveUtil;
import com.junsi.util.PageUtil;




/**   
  * @文件名: ClientController.java 
  * @包名: com.junsi.controller 
  * @类名: ClientController   
  * @时间: 2017年7月19日 上午10:43:29 2017
  * @作者: 
  * @类功能描述:TODO 客户控制层 
  */

@Controller
@RequestMapping("/client")
public class ClientController {
	
	@Autowired
	private ClientService clientService;
	
	@Autowired
	private StaffSerivce staffSerivce;
	
	@Autowired
	private RankService rankService;
	
	@Autowired
	private DepartmentSerivce departmentSerivce;

	@Autowired
	private NewrecordService newrecordService;
	
	@Autowired
	private RecordService recordService;
	@Autowired
	private CompanySerivce companySerivce;
	
	
	Logger logger=Logger.getRootLogger();
	

	/**
	 * 根据id删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteById")
	public String deleteById(Integer id){
		if(id != null){
			Boolean result = clientService.deleteById(id);
			if(result){
				return "删除成功";
			}else{
				return "删除失败";
			}			
		}else{
			return "删除失败";
		}
	}
	
	
	/**
	 * 批量删除
	 * @param ids
	 * @param response
	 * @param request
	 */
	@RequestMapping(value="/deletes")
	public void deletes(String ids,HttpServletResponse response,HttpServletRequest request){
		if(ids != null){
			String[] id = ids.split(",");
			List<Integer> integers = clientService.findByAllForId(id);
			for (Integer integer : integers) {
				Staff staff = (Staff)request.getSession().getAttribute("staff");
				if( !integer.equals(staff.getStaff_id())){
					Staff staff2 = staffSerivce.findById(integer);
					InteractiveUtil.WriteStringForHtml("无权删除所有人为: "+staff2.getStaff_name()+" 的客户信息", response);
					return;
				}
			}
			boolean b = clientService.deleteByIds(id);
			if(b){
				InteractiveUtil.WriteStringForHtml("删除成功", response);
			}else{
				InteractiveUtil.WriteStringForHtml("客户不存在删除失败", response);
			}
		}else{
			InteractiveUtil.WriteStringForHtml("客户不存在删除失败", response);
			return;
		}
	}
	
	/**
	 * 后台批量删除
	 * @param ids
	 * @param response
	 */
	@RequestMapping("/deleteByClients")
	public void deleteByClients(String ids,HttpServletResponse response){
		String[] id = ids.split(",");
		boolean b = clientService.deleteByIds(id);
		if(b){
			InteractiveUtil.WriteStringForHtml("删除成功", response);
		}else{
			InteractiveUtil.WriteStringForHtml("删除成功", response);
		}
	}
	
	/**
	 * 个人客户界面新增
	 * @param client
	 * @param request
	 * @param response
	 */
	@RequestMapping("/saveByStaff")
	public void saveSale(Client client,HttpServletRequest request,HttpServletResponse response){
		Staff staff = (Staff) request.getSession().getAttribute("staff");
		client.setClient_staffId(staff.getStaff_id());
		client.setClient_start("个人");
		boolean b = clientService.save(client);
		if(b){
			InteractiveUtil.WriteStringForHtml("新增成功", response);
		}else{
			InteractiveUtil.WriteStringForHtml("新增失败", response);
		}
	}
	@RequestMapping("/saveQian")
	public void saveQian(Client client,HttpServletRequest request,HttpServletResponse response) {
		client.setClient_start("代理");
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		client.setClient_staffId(staff.getStaff_id());
		client.setClient_departmentId(0);
		boolean b = clientService.save(client);
		if(b) {
			InteractiveUtil.WriteStringForHtml("新增成功", response);
		}else {
			InteractiveUtil.WriteStringForHtml("新增失败", response);
		}
	}
	
	/**
	 * 后台代理客户界面新增
	 * @param client
	 * @param request
	 * @param response
	 */
	@RequestMapping("/save")
	public void save(Client client,Integer start,HttpServletRequest request,HttpServletResponse response){
		client.setClient_start("代理");
		client.setClient_remarks("未开发");
		if(start != null ) {
			client.setClient_to(start);
		}
		boolean b = clientService.save(client);
		if(b){
			InteractiveUtil.WriteStringForHtml("新增成功", response);
		}else{
			InteractiveUtil.WriteStringForHtml("新增失败", response);
		}
	}
	
	/**
	 * 后台代理客户界面新增
	 * @param client
	 * @param request
	 * @param response
	 */
	@RequestMapping("/saveByPer")
	public void saveByPer(Client client,Integer start,HttpServletRequest request,HttpServletResponse response){
		client.setClient_start("个人");
		if(start != null && start ==1){
			client.setClient_to(1);
		}
		boolean b = clientService.save(client);
		if(b){
			InteractiveUtil.WriteStringForHtml("新增成功", response);
		}else{
			InteractiveUtil.WriteStringForHtml("新增失败", response);
		}
	}
	
	
	/**
	 * 进入前台客户页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/selectDepOrSta")
	public ModelAndView selectByStaff(PageUtil page,Integer start,HttpServletRequest request,HttpServletResponse response,String select){
		ModelAndView modelAndView = new ModelAndView();
		
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		String idString = (String) request.getSession().getAttribute("staffs");
		String[] id = idString.split(","); 
		List<Client> clients = new ArrayList<>();
		page.setPageSize(15);
		if(start != null && start == 1){
			Integer count = clientService.findByDepartmentOrStaffIdNumber(staff.getStaff_departmentId(), id,select,"正在跟踪");
			page.setRowCount(count);
			clients = clientService.findByDepartmentOrStaffId(staff.getStaff_departmentId(),id,page.getEndIndex(),page.getBeginIndex(),select,"正在跟踪");
			modelAndView.setViewName("forward:/client/html/qiyekehu.jsp");
		}if(start != null && start == 2){
			Integer count = clientService.findByDepartmentOrStaffIdNumber(staff.getStaff_departmentId(), id,select,"已开发");
			page.setRowCount(count);
			clients = clientService.findByDepartmentOrStaffId(staff.getStaff_departmentId(),id,page.getEndIndex(),page.getBeginIndex(),select,"已开发");
			modelAndView.setViewName("forward:/client/html/qiyekehu1.jsp");
		}
		modelAndView.addObject("clients", clients);
		List<Department> departments = departmentSerivce.findByAll();
		modelAndView.addObject("departments", departments);
		List<Record> records = recordService.listAll();
		List<Staff> staffs = staffSerivce.findByAll();
		modelAndView.addObject("staffsList", staffs);
		modelAndView.addObject("records", records);
		modelAndView.addObject("pageCount", page.getPageCount());
		modelAndView.addObject("pageNum", page.getPageNum());
		modelAndView.addObject("select", select);
		
		return modelAndView;
	}
	
	
	
	@RequestMapping("/updateById")
	public void updateById(Client client,HttpServletResponse response){
		boolean b = clientService.update(client);
		if(b){
			InteractiveUtil.WriteStringForHtml("修改成功", response);
		}else{
			InteractiveUtil.WriteStringForHtml("修改失败", response);
		}
	}
	/**
	 * 批量导入
	 * @param file
	 * @throws IOException 
	 */
	@RequestMapping("/excelImport")
	public void excelImport(@RequestParam("file") CommonsMultipartFile file,Integer start,HttpServletRequest request,HttpServletResponse response) throws IOException{
		if(!file.isEmpty()){
			String picture1 = FileUtil.fileUploe(file);
			if(!"图片上传失败".equals(picture1)){
				List<String> strings = exiclUtil(DownFile.PATH+picture1,start);
				if(strings.size() != 0){
					InteractiveUtil.WriteJsonForHtml(strings, response);
					return;
				}
			}
		}
		InteractiveUtil.WriteStringForHtml("批量导入失败，请检查文件格式", response);
	}
	
	/**
	 * 个人客户批量导入
	 * @param file
	 * @throws IOException 
	 */
	@RequestMapping("/excelImportByStaff")
	public void excelImportByStaff(@RequestParam("file") CommonsMultipartFile file,Integer start,HttpServletRequest request,HttpServletResponse response) throws IOException{
		if(!file.isEmpty()){
			String picture1 = FileUtil.fileUploe(file);
			if(!"图片上传失败".equals(picture1)){
				List<String> strings = exiclUtilByStaff(DownFile.PATH+picture1,request,start);
				if(strings.size() != 0){
					InteractiveUtil.WriteJsonForHtml(strings, response);
					return;
				}
			}
		}
		InteractiveUtil.WriteStringForHtml("批量导入失败，请检查文件格式", response);
	}
	
	
	public List<String> exiclUtil(String path,Integer start){

        // 直接读取文件:
        String filePath = path;
        File file = new File(filePath);
        InputStream is;
        XSSFSheet sheetMain;
        List<String> strings = new ArrayList<>();
        try {
        	 is = new FileInputStream(file);
             XSSFWorkbook wb = new XSSFWorkbook(is);
            // 读取第一个Sheet
            sheetMain = wb.getSheetAt(0);
            is.close();

            // 总共的行数
            int rowLens = sheetMain.getLastRowNum();
            int colLens = 6;
            int errCnt = 0;
            XSSFRow row = null;
            XSSFCell cell = null;
            String content = "";
            List<Client> clients = new ArrayList<>();
            exc:for (int rowCount = 2; rowCount <= rowLens; rowCount++) {
            	Client client = new Client();
                System.out.println("读取行：" + rowCount);
                row = sheetMain.getRow(rowCount);
                if (row != null) {
                	boolean a = true;
                    cc:for (int colCount = 0; colCount < colLens; colCount++) {
                        cell = row.getCell((short) colCount);
                        content = getCellValue(cell).trim();
                       
                        if (content == "") {
                        	if(colCount != 4 || colCount != 5 || colCount != 6 ){
                                strings.add("行 ：" + rowCount + "；列 ：" + colCount + "的内容：为空保存失败");
                                break cc;
                        	}
                            
                        }
                        if(colCount == 0){
                        	
                        }else if(colCount == 1){
                        	client.setClient_name(content);
                        	
                        }else if(colCount == 2){
                        	client.setClient_record(content);
                        	client.setClient_start("代理");
                        }else if(colCount == 3){
                        	
                        	client.setClient_phone(content);
                        }else if(colCount == 4){
                    	
                    	client.setClient_qq(content);
                        }else if(colCount == 5){
                        	List<Staff> staffs = staffSerivce.findByOneName(content);
                        	if(staffs != null && staffs.size() > 0) {
                        		client.setClient_staffId(staffs.get(0).getStaff_id());
                        	}
                        	
                        }else if(colCount == 6) {
                        	client.setClient_remarks(content);
                        }
                        
                    }
                	if(a){
                		if(start != null && start == 1){
                			client.setClient_to(start);
                		}
                		boolean b = clientService.save(client);
                    	if(b){
                    		strings.add("行 ：" + rowCount + "的内容：保存成功");
                    	}else{
                    		strings.add("行 ：" + rowCount + "的内容：保存失败");
                    	}
                	}
                    	
                }
                clients.add(client);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strings;
    }
	
	
	public List<String> exiclUtilByStaff(String path,HttpServletRequest request,Integer start){
		
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		Integer id = staff.getStaff_id();
        // 直接读取文件:
        String filePath = path;
        File file = new File(filePath);
        InputStream is;
        XSSFSheet sheetMain;
        List<String> strings = new ArrayList<>();
        try {
            is = new FileInputStream(file);
            XSSFWorkbook wb = new XSSFWorkbook(is);
            // 读取第一个Sheet
            sheetMain = wb.getSheetAt(0);
            is.close();

            // 总共的行数
            int rowLens = sheetMain.getLastRowNum();
            int colLens = 6;
            int errCnt = 0;
            XSSFRow row = null;
            XSSFCell cell = null;
            String content = "";
            List<Client> clients = new ArrayList<>();
            exc:for (int rowCount = 2; rowCount <= rowLens; rowCount++) {
            	Client client = new Client();
                System.out.println("读取行：" + rowCount);
                row = sheetMain.getRow(rowCount);
                if (row != null) {
                	boolean a = true;
                    cc:for (int colCount = 0; colCount < colLens; colCount++) {
                        cell = row.getCell((short) colCount);
                        content = getCellValue(cell).trim();
                       

                        if (content == "") {
                        	if(colCount != 3){
                        		
                                strings.add("行 ：" + rowCount + "；列 ：" + colCount + "的内容：为空保存失败");
                                break cc;
                        	}
                            
                        }
                        
                        if(colCount == 0){
                        	
                        }else if(colCount == 1){
                        	client.setClient_name(content);
                        	
                        }else if(colCount == 2){
                        	client.setClient_record(content);
                        	client.setClient_start("个人");
                        }else if(colCount == 3){
                        	
                        	client.setClient_phone(content);
                        }else if(colCount == 4){
                    	
                    	client.setClient_qq(content);
                        }else if(colCount == 5){
                        	List<Staff> staffs = staffSerivce.findByOneName(content);
                        	if(staffs != null && staffs.size() > 0) {
                        		client.setClient_staffId(staffs.get(0).getStaff_id());
                        	}
                        	
                        }else if(colCount == 6) {
                        	client.setClient_remarks(content);
                        }
                        
                    }
                	if(a){
                		if(start != null){
                			client.setClient_to(start);
                		}
                		boolean b = clientService.save(client);
                    	if(b){
                    		strings.add("行 ：" + rowCount + "的内容：保存成功");
                    	}else{
                    		strings.add("行 ：" + rowCount + "的内容：保存失败");
                    	}
                	}
                    	
                }
                clients.add(client);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strings;
    }

	
	public static String getCellValue(XSSFCell cell) {
	    if (cell != null) {
	        switch (cell.getCellType()) {
	        case XSSFCell.CELL_TYPE_BLANK:
	            return "";
	        case XSSFCell.CELL_TYPE_NUMERIC:
	            String strValue = String.valueOf(cell.getNumericCellValue());
	            if (strValue != null && strValue.indexOf(".") != -1
	                    && strValue.indexOf("E") != -1) {
	                try {
	                    return new DecimalFormat().parse(strValue).toString();
	                } catch (ParseException e) {
	                    e.printStackTrace();
	                }
	            } else {
	                if (strValue.endsWith(".0")) {
	                    return strValue.substring(0, strValue.indexOf(".0"));
	                } else {
	                    return strValue;
	                }
	            }
	        case XSSFCell.CELL_TYPE_STRING:
	            return (cell.getStringCellValue() + "").trim();
	        case XSSFCell.CELL_TYPE_FORMULA:
	            return (cell.getCellFormula() + "").trim();
	        case XSSFCell.CELL_TYPE_BOOLEAN:
	            return cell.getBooleanCellValue() + "";
	        case XSSFCell.CELL_TYPE_ERROR:
	            return cell.getErrorCellValue() + "";
	        }
	    }
	    return "";
	}
   
   
	@RequestMapping("/selectByAll")
    public ModelAndView selectByAll(Integer classfiy,String select,HttpServletRequest request){
    	ModelAndView modelAndView = new ModelAndView();
    	Staff staff = (Staff)request.getSession().getAttribute("staff");
		String idString = (String) request.getSession().getAttribute("staffs");
		String[] id = idString.split(","); 
		List<Client> clients = new ArrayList<>();
		if(classfiy != null && classfiy == 1){
			clients = clientService.findByDepartmentOrStaffIdAndSelect(staff.getStaff_departmentId(),id,select);
			modelAndView.setViewName("forward:../client/html/qiyekehu.jsp");
		}else{
			/*clients = clientService.findByStaffIdAndSelect(id,select);
			modelAndView.setViewName("forward:../client/html/gerenkehu.jsp");
			List<Rank> ranks = rankService.listAll();
			modelAndView.addObject("ranks", ranks);*/
		}
		modelAndView.addObject("clients", clients);
		List<Department> departments = departmentSerivce.findByAll();
		modelAndView.addObject("departments", departments);
		List<Staff> staffs = staffSerivce.findByAll();
		modelAndView.addObject("staffsList", staffs);
		return modelAndView;
    }
    
   
	@RequestMapping("/findByAllForAgent")
    public ModelAndView findByAllForPersonal(Integer start,PageUtil page,String select,HttpServletRequest request){
    	ModelAndView modelAndView = new ModelAndView();
    	List<Client> clients = new ArrayList<>();
    	page.setPageSize(15);
    	//0为未开发,1为正在跟踪，2为已开发，3为回收
    	String state = null;
    	if(start == 0) {
    		state = "未开发";
    		modelAndView.setViewName("forward:../client/html/daili.jsp");
    	}else if(start == 1){
    		state = "正在跟踪";
    		modelAndView.setViewName("forward:../client/html/dailiyifen2.jsp");
    	}else if(start == 2){
    		state = "已开发";
    		modelAndView.setViewName("forward:../client/html/daliyifen.jsp");
    	}else if(start == 3){
    		state = "已回收";
    		modelAndView.setViewName("forward:../client/html/dailihuishou.jsp");
    	}
		Integer count = clientService.findByAllForAgentOneNumber(state,select);
		page.setRowCount(count);
		clients = clientService.findByAllForAgentOne(page.getEndIndex(),page.getBeginIndex(),select,state);
    	
    	modelAndView.addObject("clients", clients);
    	List<Rank> ranks = rankService.listAll();
    	modelAndView.addObject("ranks", ranks);
    	List<Department> departments = departmentSerivce.findByAll();
    	List<Staff> staffs = staffSerivce.findByAll();
    	modelAndView.addObject("departments", departments);
    	modelAndView.addObject("staffList", staffs);
    	modelAndView.addObject("pageCount", page.getPageCount());
		modelAndView.addObject("pageNum", page.getPageNum());
		modelAndView.addObject("select", select);
		request.getSession().setAttribute("dailiClient", clientService.findByAllForAgentOne(999999,0,select,state));
    	
    	return modelAndView;
    }
    
   /**
    * 按条件对代理客户和已分配个人客户进行查询
    * @param start
    * @param select
    * @param classfiy
    * @return
    */
	@RequestMapping(value="/findByAllFroSelect")
    public ModelAndView findByAllFroSelect(Integer start,String select,Integer classfiy){
    	ModelAndView modelAndView = new ModelAndView();
    	List<Client> clients = new ArrayList<>();
    	//1为代理客户
    	if(classfiy != null && classfiy == 1){
    		//1为未分配
    		if(start != null && start == 1){
    			clients = clientService.findByAllFroSelect("代理",select);
    			modelAndView.setViewName("forward:../client/html/daili.jsp");
    		}else{
    			clients = clientService.findByAllFroSelectByNo("代理",select);
    			modelAndView.setViewName("forward:../client/html/dailiyifen.jsp");
    		}
    	}else{
    		clients = clientService.findByAllFroSelectByyifen(select);
    		modelAndView.setViewName("forward:../client/html/kehuyifen.jsp");
    	}
    	modelAndView.addObject("clients", clients);
    	List<Rank> ranks = rankService.listAll();
    	modelAndView.addObject("ranks", ranks);
    	List<Department> departments = departmentSerivce.findByAll();
    	List<Staff> staffs = staffSerivce.findByAll();
    	modelAndView.addObject("departments", departments);
    	modelAndView.addObject("staffList", staffs);
    	
    	
    	return modelAndView;
    }
	/**
	 * 按条件搜索未分配的用户信息
	 * @param start
	 * @param select
	 * @param classfiy
	 * @return
	 *//*
	@RequestMapping(value="/findByAllFroSelectByGRDataweifen")
    public ModelAndView findByAllFroSelectByGRDataweifen(String select){
    	ModelAndView modelAndView = new ModelAndView();
    	List<Client> clients = new ArrayList<>();
    	clients = clientService.findByAllFroSelectByGRDataweifen(select);
    	modelAndView.setViewName("forward:../client/html/kehuguanli.jsp");
    
    	modelAndView.addObject("clients", clients);
    	List<Rank> ranks = rankService.listAll();
    	modelAndView.addObject("ranks", ranks);
    	List<Department> departments = departmentSerivce.findByAll();
    	List<Staff> staffs = staffSerivce.findByAll();
    	modelAndView.addObject("departments", departments);
    	modelAndView.addObject("staffList", staffs);
    	
    	
    	return modelAndView;
    }*/
   
	
	/**
	 * 新后台已开发用户重新分配对应的角色
	 * @param client_id
	 * @param depId
	 * @param staff_id
	 * @param response
	 */
	@RequestMapping("/updateStaffId")
    public void updateStaffId(String client_id,Integer depId,Integer staff_id,HttpServletResponse response){
    	String[] id = client_id.split(",");
    	Integer[] ids = new Integer[id.length];
    	 for(int i=0;i<ids.length;i++){
    		 ids[i] = Integer.parseInt(id[i]);
	    }
    	 if(staff_id == null || staff_id.equals("")){
    		 staff_id = 0;
    	 }else{
    		 depId = 0;
    	 }
    	 String remakes="已开发";
    	boolean b = clientService.updateByAgent(ids, staff_id, depId,remakes);
    	if(b){
    		InteractiveUtil.WriteStringForHtml("分配成功", response);
    	}else{
    		InteractiveUtil.WriteStringForHtml("分配失败", response);
    	}
    }
    
    /**
     * 用户开发已分配客户，后台
     * @param page
     * @return
     */
	@RequestMapping("/findByAllGr")
    public ModelAndView findByAllGr(PageUtil page){
    	ModelAndView modelAndView = new ModelAndView();
    	page.setPageSize(10);
    	Integer count = clientService.findByAllPersonalNumberyifen();
    	page.setRowCount(count);
    	List<Client> clients = clientService.findByAllPersonalyifen(page.getEndIndex(),page.getBeginIndex());
    	modelAndView.addObject("clients", clients);
    	List<Rank> ranks = rankService.listAll();
    	modelAndView.addObject("ranks", ranks);
    	List<Department> departments = departmentSerivce.findByAll();
    	List<Staff> staffs = staffSerivce.findByAll();
    	modelAndView.addObject("departments", departments);
    	modelAndView.addObject("staffList", staffs);
    	modelAndView.addObject("pageCount", page.getPageCount());
		modelAndView.addObject("pageNum", page.getPageNum());
		
    	modelAndView.setViewName("forward: weifencount.action?zhuizong=0");
    	return modelAndView;
    }
	/**
	 * 新用户开发未分配客户和正在跟踪客户，后台,分页的入口
	 * @param staff
	 * @param file
	 * @return
	 */
	@RequestMapping("/weifencount")
	 public ModelAndView weifencount(PageUtil page,HttpServletResponse response,HttpServletRequest request,String select,String zhuizong){
		ModelAndView modelAndView=new ModelAndView();
		page.setPageSize(10);
		if(zhuizong.equals("0")){
		if(StringUtils.isBlank(select)){
			Integer count = clientService.findByAllPersonalNumberweifen();
			page.setRowCount(count);
		}else{
			Integer count = clientService.findByAllFroSelectByGRDataweifenzongshu(select);
			page.setRowCount(count);
		}
		modelAndView.addObject("PageCount", page.getPageCount());
		modelAndView.addObject("PageNum", page.getPageNum());
		modelAndView.addObject("select", select);
		modelAndView.setViewName("forward:../client/html/kehuguanli.jsp");
		}
		if(zhuizong.equals("1")){
		if(StringUtils.isBlank(select)){
			Integer count = clientService.findByAllPersonalNumbergenzong();
			page.setRowCount(count);
		}else{
			Integer count = clientService.findByAllFroSelectByGRDatagenzhongshu(select);
			page.setRowCount(count);
		}
		modelAndView.addObject("PageCount", page.getPageCount());
		modelAndView.addObject("PageNum", page.getPageNum());
		modelAndView.addObject("select", select);
		modelAndView.setViewName("forward:../client/html/hgengzong.jsp");
		}
		if(zhuizong.equals("2")){
		if(StringUtils.isBlank(select)){
			Integer count = clientService.findByAllPersonalNumberyifen();
			page.setRowCount(count);
		}else{
			Integer count = clientService.findByAllFroSelectByGRDatakaifashu(select);
			page.setRowCount(count);
		}
			modelAndView.addObject("PageCount", page.getPageCount());
			modelAndView.addObject("PageNum", page.getPageNum());
			modelAndView.addObject("select", select);
			modelAndView.setViewName("forward:../client/html/kehuyifen.jsp");
		}
		if(zhuizong.equals("3")){
			if(StringUtils.isBlank(select)){
				Integer count = clientService.findByAllPersonalNumberyihuishou();
				page.setRowCount(count);
			}else{
				Integer count = clientService.findByAllFroSelectByGRDatahuishoushu(select);
				page.setRowCount(count);
			}
			modelAndView.addObject("PageCount", page.getPageCount());
			modelAndView.addObject("PageNum", page.getPageNum());
			modelAndView.addObject("select", select);
			modelAndView.setViewName("forward:../client/html/huishou.jsp");
		}
		//显示新增时下拉框里的名字选项
		List<Rank> ranks = rankService.listAll();
    	modelAndView.addObject("ranks", ranks);
    	List<Department> departments = departmentSerivce.findByAll();
    	List<Staff> staffs = staffSerivce.findByAll();
    	modelAndView.addObject("departments", departments);
    	modelAndView.addObject("staffList", staffs);
		return modelAndView;
	}
	
	/**
	 * 用户开发未开发客户，后台,分页
	 * 
	 * @param 
	 */
	@RequestMapping("/findByAllweifenhuke1")
	public void findByAllweifenhuke1(PageUtil page,String statu,String select,HttpServletResponse response,HttpServletRequest request){
		if(!"".equals(select) && select!=null){
			page.setPageSize(10);
			Integer count = clientService.findByAllFroSelectByGRDataweifenzongshu(select);
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllFroSelectByGRDataweifen(select,page.getEndIndex(),page.getBeginIndex());
				
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}	
		}else{
			page.setPageSize(10);
			Integer count = clientService.findByAllPersonalNumberweifen();
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllPersonalweifen(page.getEndIndex(),page.getBeginIndex());
				
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}
		}	
	}
	/**
	 * 用户开发正在跟踪客户，后台,分页
	 * 
	 * @param 
	 */
	@RequestMapping("/findByAllgenzonghuke")
	public void findByAllgenzonghuke(PageUtil page,String statu,String selectgen,HttpServletResponse response,HttpServletRequest request){
		if(!"".equals(selectgen) && selectgen!=null){
			page.setPageSize(10);
			Integer count = clientService.findByAllFroSelectByGRDatagenzhongshu(selectgen);
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllFroSelectByGRDatagenzong(selectgen,page.getEndIndex(),page.getBeginIndex());
				if(clients.size()>0){
					for (Client client : clients) {
						Staff staff=staffSerivce.findById(client.getClient_staffId());
						if(staff!=null){
						client.setNewstaffName(staff.getStaff_name());
						}
					}
				}
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}	
		}else{
			page.setPageSize(10);
			Integer count = clientService.findByAllPersonalNumbergenzong();
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllPersonalgengzong(page.getEndIndex(),page.getBeginIndex());
				if(clients.size()>0){
					for (Client client : clients) {
						Staff staff=staffSerivce.findById(client.getClient_staffId());
						if(staff!=null){
						client.setNewstaffName(staff.getStaff_name());
						}
					}
				}
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}
		}	
	}
	/**
	 * 用户开发已开发客户，后台,分页
	 * 
	 * @param 
	 */
	@RequestMapping("/findByAllyikaifahuke")
	public void findByAllyikaifahuke(PageUtil page,String statu,String selectgen,HttpServletResponse response,HttpServletRequest request){
		if(!"".equals(selectgen) && selectgen!=null){
			page.setPageSize(10);
			Integer count = clientService.findByAllFroSelectByGRDatakaifashu(selectgen);
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllFroSelectByGRDatachayikaifa(selectgen,page.getEndIndex(),page.getBeginIndex());
				if(clients.size()>0){
					for (Client client : clients) {
						Staff staff=staffSerivce.findById(client.getClient_staffId());
						if(staff!=null){
						client.setNewstaffName(staff.getStaff_name());
						}
					}
				}
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}	
		}else{
			page.setPageSize(10);
			Integer count = clientService.findByAllPersonalNumberyifen();
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllPersonalyifen(page.getEndIndex(),page.getBeginIndex());
				if(clients.size()>0){
					for (Client client : clients) {
						Staff staff=staffSerivce.findById(client.getClient_staffId());
						if(staff!=null){
						client.setNewstaffName(staff.getStaff_name());
						}
					}
				}
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}
		}	
	}
	/**
	 * 用户开发回收客户，后台,分页
	 * 
	 * @param 
	 */
	@RequestMapping("/findByAllhuishou")
	public void findByAllhuishou(PageUtil page,String statu,String select,HttpServletResponse response,HttpServletRequest request){
		if(!"".equals(select) && select!=null){
			page.setPageSize(10);
			Integer count = clientService.findByAllFroSelectByGRDatahuishoushu(select);
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllFroSelectByGRDatachayihuishou(select,page.getEndIndex(),page.getBeginIndex());
				
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}	
		}else{
			page.setPageSize(10);
			Integer count = clientService.findByAllPersonalNumberyihuishou();
			if(count != null){
				page.setRowCount(count);
				//根据员工ID来查找销售机会
				List<Client> clients = clientService.findByAllPersonalhuishou(page.getEndIndex(),page.getBeginIndex());
				
			response.setContentType("text/json; charset=UTF-8");
			InteractiveUtil.WriteJsonForPage(clients, page, response);
			}
		}	
	}
    /**
     * 新后台为未开发用户分配角色，分配完后状态为正在跟踪
     * @param client_id
     * @param depId
     * @param staff_id
     * @param response
     */
	@RequestMapping("/updateByPer")
    public void updateByPer(String client_id,Integer depId,Integer staff_id,HttpServletResponse response,String select){
    	String[] id = client_id.split(",");
    	Integer[] ids = new Integer[id.length];
    	 for(int i=0;i<ids.length;i++){
    		 ids[i] = Integer.parseInt(id[i]);
	     }
    	 String remakes=null;
    	 if(select.equals("0")){
    		 remakes="正在跟踪";
    	 }
    	 if(select.equals("1")){
    		 remakes="已开发";
    	 }
    	 if(select.equals("2")){
    		 remakes="已回收";
         }
    	boolean b = clientService.updateByAgent(ids, staff_id, depId,remakes);
    	if(b){
    		InteractiveUtil.WriteStringForHtml("分配成功", response);
    	}else{
    		InteractiveUtil.WriteStringForHtml("分配失败", response);
    	}
    }
    
    
	@RequestMapping(value="/findById")
    public void findById(String client_id,HttpServletResponse response){
    	Client client = clientService.findById(Integer.valueOf(client_id));
    	if(client != null){
    		if(client.getClient_staffId()!=null){
    		Staff staff=staffSerivce.findById(client.getClient_staffId());
			if(staff!=null){
			client.setNewstaffName(staff.getStaff_name());
			}
    		}
    		InteractiveUtil.WriteBeanForHtml(client, response);
    	}else{
    		InteractiveUtil.WriteStringForHtml("数据不存在，请刷新重试", response);
    	}
    }
    
    
	@RequestMapping("/downFile")
	public void downFile(HttpServletResponse response,HttpServletRequest request,String state) throws IOException{
		if(state != null && "1".equals(state)) {
			DownFile.download(DownFile.PATH+"file/dailikehu.xlsx", response, request);	
		}else {
			DownFile.download(DownFile.PATH+"file/kehu.xlsx", response, request);	
		}
		
	}
    
   
	@RequestMapping("/newrecord")
    public ModelAndView newrecord(Integer id){
    	ModelAndView modelAndView = new ModelAndView();
    	Client client = clientService.findById(id);
    	if(client != null){
    		List<Newrecord> newrecords = newrecordService.findByClientId(id);
    		modelAndView.addObject("newrecords", newrecords);
    		modelAndView.addObject("client", client);
    		modelAndView.setViewName("../new/html/another.jsp");
    	}
    	return modelAndView;
    }
    
    
	@RequestMapping("/exportClient")
    public void exportClient(String id,String start,Integer classify,HttpServletRequest request,HttpServletResponse response) throws Exception{
		PageUtil page=new PageUtil();
		page.setPageNum(Integer.valueOf(id));
		page.setPageSize(10);
    	Integer count = 1;
    	List<Staff> staffs = staffSerivce.findByAll();
    	if("0".equals(start)) {//0:客户资料》用户资料，1：客户资料》代理资料，2：资料开发》用户资料，3客户资料》代理开发
    		count = clientService.findByAllPersonalNumbers();
    		page.setRowCount(count);
    		List<Client> clients = clientService.findAllPersonals();
    		for (Client client : clients) {
    			for (Staff s : staffs) {
    				String staff_id=s.getStaff_id().toString();
    				if(staff_id!=null && client.getClient_staffId()!=null) {
    					if (staff_id.equals(client.getClient_staffId().toString())) {
        					client.setStaff_name(s.getStaff_name());
        					
        				}
    				}
    				
    			}
    			
    		
    		}
    		DownlaodExcel.ClientExcel(response, clients,"用户资料");
    	}else if("1".equals(start)) {
    		count = clientService.findByAllAgentDataNumber();
    		page.setRowCount(count);
    		List<Client> clients = clientService.findAllAgentData();
    		for (Client client : clients) {
    			for (Staff s : staffs) {
    				String staff_id=s.getStaff_id().toString();
    				if(staff_id!=null && client.getClient_staffId()!=null) {
    				if (staff_id.equals(client.getClient_staffId().toString())) {
    					client.setStaff_name(s.getStaff_name());
    					
    				}
    				}
    			}
    			
    		
    		}
    		DownlaodExcel.ClientExcel(response, clients,"代理资料");
    	}else if("2".equals(start)) {
    		 count = clientService.findByAllPersonalNumber();
        	page.setRowCount(count);
        	List<Client> clients = clientService.findAllyifenPersonal();
        	for (Client client : clients) {
    			for (Staff s : staffs) {
    				String staff_id=s.getStaff_id().toString();
    				if(client.getClient_staffId()!=null && !"".equals(client.getClient_staffId().toString())) {
    					if (staff_id.equals(client.getClient_staffId().toString())) {
        					client.setStaff_name(s.getStaff_name());
        					
        				}
    				}
    			}
    			
    		
    		}
    		DownlaodExcel.ClientExcel(response, clients,"已分配用户资料");
    	}else if("3".equals(start)) {
    		/*count = clientService.findByAllForAgentOneNumber();
    		page.setRowCount(count);
    		List<Client> clients = clientService.findAllForAgentOne();
    		for (Client client : clients) {
    			for (Staff s : staffs) {
    				String staff_id=s.getStaff_id().toString();
    				if(client.getClient_staffId()!=null && !"".equals(client.getClient_staffId().toString())) {
    					if (staff_id.equals(client.getClient_staffId().toString())) {
        					client.setStaff_name(s.getStaff_name());
        					
        				}
    				}
    			}
    			
    		
    		}
    		DownlaodExcel.ClientExcel(response, clients,"代理资料");*/
    	}else if("4".equals(start)) {
    		count = clientService.findByAllPersonalNumber();
        	page.setRowCount(count);
        	List<Client> clients = clientService.findAllweifenPersonal();
        	for (Client client : clients) {
    			for (Staff s : staffs) {
    				String staff_id=s.getStaff_id().toString();
    				if(client.getClient_staffId()!=null && !"".equals(client.getClient_staffId().toString())) {
    					if (staff_id.equals(client.getClient_staffId().toString())) {
        					client.setStaff_name(s.getStaff_name());
        					
        				}
    				}
    			}
   			
   		
   		}
   		DownlaodExcel.ClientExcel(response, clients,"未分配用户资料");
   	}
	}
		/*List<Client> clients = new ArrayList<>();
    	if(id != null && !"null".equals(id)){
    		
    		String[] ids = id.split(",");
    		clients = clientService.findByAlls(ids);
    	}else{
    		
    		if(start != null && start == 1){
    			//代理开发已经分配
    			if(classify != null && classify == 1){
    				
    				clients = clientService.findByAllForAgentOne(1000000, 0);
    				
    			}else{
    				
    				//代理开发未分配
    				clients = clientService.findByAllForAgentTwo(1000000, 0);
    				
    			}
    		}else if(start != null && start == 2){
    			
    			clients = clientService.findByAllPersonals(1000000, 0);
    			
    		}else if(start != null && start == 3){
    			
    			clients = clientService.findByAllAgentData(1000000, 0);
    			
    		}else{
    			//用户开发
    			clients = clientService.findByAllPersonal(10000000, 0);
    		}
    		
    	}
    	String path = DownFile.PATH+"client.xlsx";
    	CreateSimpleExcelToDisk.daoru(clients, path);
    	DownFile.download(path, response, request);
    }
    

*/
    @RequestMapping("/adopt")
    public void adopt(String id,HttpServletResponse response){
    	if(id != null){
    		String[] ids = id.split(",");
    		boolean b = clientService.updateByTo(ids);
    		if(b){
    			InteractiveUtil.WriteStringForHtml("成功通过", response);
    			return;
    		}
    	}
    	InteractiveUtil.WriteStringForHtml("通过失败", response);
    	
    }
    

	/**
	 * 进入前台客户资料页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/selectByStaffAnd")
	public ModelAndView selectByStaffAnd(PageUtil page,Integer start,HttpServletRequest request,HttpServletResponse response){
		
		ModelAndView modelAndView = new ModelAndView();
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		String idString = (String) request.getSession().getAttribute("staffs");
		String[] id = idString.split(","); 
		List<Client> clients = new ArrayList<>();
		page.setPageSize(10);
		if(start != null && start == 1){
			
			Integer count = clientService.findByDepartmentOrStaffIdNumbers(staff.getStaff_departmentId(), id);
			page.setRowCount(count);
			clients = clientService.findByDepartmentOrStaffIds(staff.getStaff_departmentId(),id,page.getEndIndex(),page.getBeginIndex());
			modelAndView.setViewName("forward:/client/html/dailiziliao.jsp");
		}else{
			
			Integer count = clientService.findByStaffIdNumbers(id);
			page.setRowCount(count);
			clients = clientService.findByStaffIds(id,page.getEndIndex(),page.getBeginIndex());
			modelAndView.setViewName("forward:/client/html/yonghuziliao.jsp");
			/*List<Rank> ranks = rankService.listAll();
			modelAndView.addObject("ranks", ranks);*/
		}
		modelAndView.addObject("clients", clients);
		List<Department> departments = departmentSerivce.findByAll();
		modelAndView.addObject("departments", departments);
		List<Record> records = recordService.listAll();
		List<Staff> staffs = staffSerivce.findByAll();
		modelAndView.addObject("staffsList", staffs);
		modelAndView.addObject("records", records);
		modelAndView.addObject("pageCount", page.getPageCount());
		modelAndView.addObject("pageNum", page.getPageNum());
		
		return modelAndView;
	}
	
	
	/**
	 * 后台进入用户客户资料
	 */
	@RequestMapping("/findByAllData")
    public ModelAndView findByAllData(PageUtil page,Integer start){
    	ModelAndView modelAndView = new ModelAndView();
    	page.setPageSize(10);
    	Integer count = 1;
    	
    	List<Client> clients = new ArrayList<>();
    	if(start != null && start ==1){
    		count = clientService.findByAllPersonalNumbers();
    		page.setRowCount(count);
    		clients = clientService.findByAllPersonals(page.getEndIndex(),page.getBeginIndex());
    		modelAndView.setViewName("forward:../client/html/kehuyifen2.jsp");//--------------------------------------
    	}else{
    		count = clientService.findByAllAgentDataNumber();
    		page.setRowCount(count);
    		clients = clientService.findByAllAgentData(page.getEndIndex(),page.getBeginIndex());
    		modelAndView.setViewName("forward:../client/html/kehuyifen3.jsp");//--------------------------------------
    	}
    	
    	modelAndView.addObject("clients", clients);
    	/*List<Rank> ranks = rankService.listAll();
    	modelAndView.addObject("ranks", ranks);*/
    	List<Record> records = recordService.listAll();
    	List<Company> companies=companySerivce.findByAll();
    	List<Department> departments = departmentSerivce.findByAll();
    	List<Staff> staffs = staffSerivce.findByAll();
    	modelAndView.addObject("records", records);
    	modelAndView.addObject("departments", departments);
    	modelAndView.addObject("staffList", staffs);
    	modelAndView.addObject("pageCount", page.getPageCount());
		modelAndView.addObject("pageNum", page.getPageNum());
		modelAndView.addObject("companies", companies);
    	return modelAndView;
    }
	
	/**
	 * 后台客户资料条件查询
	 * @param select
	 * @param classfiy
	 * @return
	 */
	@RequestMapping(value="/findByAllDataSelect")
    public ModelAndView findByAllDataSelect(String select,Integer classfiy){
    	ModelAndView modelAndView = new ModelAndView();
    	List<Client> clients = new ArrayList<>();
    	
    	if(classfiy != null && classfiy == 1){
    		clients = clientService.findByAllFroSelectData("代理",select);
    		modelAndView.setViewName("forward:../client/html/kehuyifen3.jsp");//----------------------
    	}else{
    		clients = clientService.findByAllFroSelectByGRData(select);
    		modelAndView.setViewName("forward:../client/html/kehuyifen2.jsp");//----------------------
    	}
    	modelAndView.addObject("clients", clients);
    	/*List<Rank> ranks = rankService.listAll();
    	modelAndView.addObject("ranks", ranks);*/
    	List<Department> departments = departmentSerivce.findByAll();
    	List<Staff> staffs = staffSerivce.findByAll();
    	modelAndView.addObject("departments", departments);
    	modelAndView.addObject("staffList", staffs);
    	
    	
    	return modelAndView;
    }
	
	/**
	 * 前台客户资料条件查询
	 * @param classfiy
	 * @param select
	 * @param request
	 * @return
	 */
	@RequestMapping("/selectByAllData")
    public ModelAndView selectByAllData(Integer classfiy,String select,HttpServletRequest request){
    	ModelAndView modelAndView = new ModelAndView();
    	Staff staff = (Staff)request.getSession().getAttribute("staff");
		String idString = (String) request.getSession().getAttribute("staffs");
		String[] id = idString.split(","); 
		List<Client> clients = new ArrayList<>();
		if(classfiy != null && classfiy == 1){
			clients = clientService.findByDepartmentOrStaffIdAndSelects(staff.getStaff_departmentId(),id,select);
			modelAndView.setViewName("forward:../client/html/dailiziliao.jsp");
		}else{
			clients = clientService.findByStaffIdAndSelects(id,select);
			modelAndView.setViewName("forward:../client/html/yonghuziliao.jsp");
			/*List<Rank> ranks = rankService.listAll();
			modelAndView.addObject("ranks", ranks);*/
		}
		modelAndView.addObject("clients", clients);
		List<Department> departments = departmentSerivce.findByAll();
		modelAndView.addObject("departments", departments);
		List<Staff> staffs = staffSerivce.findByAll();
		modelAndView.addObject("staffsList", staffs);
		return modelAndView;
    }
	
	 /** 
     * 新后台用户开发模块的批量导入
     * @param request 
     * @param response 
     * @throws Exception 
     */  
    @ResponseBody  
    @RequestMapping("/daoru")  
    public  void  ajaxUploadExcel(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {    
        InputStream in =null;  
        List<List<Object>> listob = null;  
        if(file.isEmpty()){  
            throw new Exception("文件不存在！");  
        }  
          
        in = file.getInputStream();  
        listob = new DaoRuExcel().getBankListByExcel(in,file.getOriginalFilename());  
        Boolean result = null;
        //该处可调用service相应方法进行数据保存到数据库中，现只对数据输出  
        for (int i = 0; i < listob.size(); i++) {  
            List<Object> lo = listob.get(i);
            Client client=new Client();
            client.setClient_name(String.valueOf(lo.get(1)));  
            client.setClient_qq(String.valueOf(lo.get(2)));
            client.setClient_phone(String.valueOf(lo.get(3)));
            client.setClient_record(String.valueOf(lo.get(4)));
            client.setClient_remarks("未开发");
            client.setClient_start("个人");
             result=clientService.save(client);
        }
        if(result){
        	InteractiveUtil.WriteStringForHtml("导入成功", response);
        }else{
        	InteractiveUtil.WriteStringForHtml("发生未知问题,导入失败", response);
        }
       
    }
    
    /** 
     * 新后台代理开发模块的批量导入
     * @param request 
     * @param response 
     * @throws Exception 
     */  
    @ResponseBody  
    @RequestMapping("/dailidaoru")  
    public  void  dailidaoruExcel(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {    
        InputStream in =null;  
        List<List<Object>> listob = null;  
        if(file.isEmpty()){  
            throw new Exception("文件不存在！");  
        }  
          
        in = file.getInputStream();  
        listob = new DaoRuExcel().getBankListByExcel(in,file.getOriginalFilename());  
        Boolean result = null;
        //该处可调用service相应方法进行数据保存到数据库中，现只对数据输出  
        for (int i = 0; i < listob.size(); i++) {  
            List<Object> lo = listob.get(i);
            Client client=new Client();
            client.setCompany_fuzeren(String.valueOf(lo.get(1)));  
            client.setClient_qq(String.valueOf(lo.get(2)));
            client.setCompany_name(String.valueOf(lo.get(3)));
            client.setClient_phone(String.valueOf(lo.get(4)));
            client.setClient_record(String.valueOf(lo.get(5)));
            client.setClient_remarks("未开发");
            client.setClient_start("代理");
             result=clientService.save(client);
        }
        if(result){
        	InteractiveUtil.WriteStringForHtml("导入成功", response);
        }else{
        	InteractiveUtil.WriteStringForHtml("发生未知问题,导入失败", response);
        }
       
    }
    /**
	 * 新后台用户开发模块的导出
	 * @return
	 */
	@RequestMapping("/daochuweifen")
	public ModelAndView findAllNews(HttpServletResponse response,HttpServletRequest request,String select) {
		 	String fileName="用户开发";
		 	String name="0";
		 	List<Client> client=null;
		 	if(select.equals("0")){
		 		client=clientService.findAllweifenPersonal();
		 	}
		 	if(select.equals("1")){
		 		client=clientService.findAllyifenPersonalhuishoua();
		 	}
	        //填充projects数据
	        
	        List<Map<String,Object>> list=createExcelRecord(client,name);
	        String columnNames[]={"编号","客户姓名","联系QQ","电话","来源渠道","追踪情况"};//列名
	        String keys[]   =    {"client_id","client_name","client_qq","client_phone","client_record","client_remarks"};//map中的key
	        ByteArrayOutputStream os = new ByteArrayOutputStream();
	        try {
	            DaoChuExcel.createWorkBook(list,keys,columnNames).write(os);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        byte[] content = os.toByteArray();
	        InputStream is = new ByteArrayInputStream(content);
	        // 设置response参数，可以打开下载页面
	        ServletOutputStream out = null;
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
				try {
					response.reset();
					response.setContentType("application/vnd.ms-excel;charset=utf-8");
					response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
					out = response.getOutputStream();
					bis = new BufferedInputStream(is);
					bos = new BufferedOutputStream(out);
					byte[] buff = new byte[2048];
					int bytesRead;
					// Simple read/write loop.
					while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					    bos.write(buff, 0, bytesRead);
					}
					if (bis != null)
					    bis.close();
					if (bos != null)
					    bos.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

	        return null;
	    }
	 /**
		 * 新后台用户代理模块的导出
		 * @return
		 */
		@RequestMapping("/dailidaochuweifen")
		public ModelAndView dailidaochuweifen(HttpServletResponse response,HttpServletRequest request,String select) {
			 	String fileName="代理开发";
			 	String name="0";
			 	List<Client> client= (List<Client>)request.getSession().getAttribute("dailiClient");
		        
		        List<Map<String,Object>> list=dailiExcelRecord(client,name);
		        String columnNames[]={"编号","公司负责人","电话","联系QQ","公司名称","所有人","来源渠道","追踪情况"};//列名
		        String keys[]   =    {"client_id","company_fuzeren","client_phone","client_qq","company_name","newstaffName","client_record","client_remarks"};//map中的key
		        ByteArrayOutputStream os = new ByteArrayOutputStream();
		        try {
		            DaoChuExcel.createWorkBook(list,keys,columnNames).write(os);
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		        byte[] content = os.toByteArray();
		        InputStream is = new ByteArrayInputStream(content);
		        // 设置response参数，可以打开下载页面
		        ServletOutputStream out = null;
				BufferedInputStream bis = null;
				BufferedOutputStream bos = null;
					try {
						response.reset();
						response.setContentType("application/vnd.ms-excel;charset=utf-8");
						response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
						out = response.getOutputStream();
						bis = new BufferedInputStream(is);
						bos = new BufferedOutputStream(out);
						byte[] buff = new byte[2048];
						int bytesRead;
						// Simple read/write loop.
						while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
						    bos.write(buff, 0, bytesRead);
						}
						if (bis != null)
						    bis.close();
						if (bos != null)
						    bos.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

		        return null;
		    }
	
	/**
	 * 新后台用户开发模块的导出
	 * @return
	 */
	@RequestMapping("/daochugenzong")
	public ModelAndView daochugenzong(HttpServletResponse response,HttpServletRequest request,String name) {
		 	String fileName="用户开发";
		 	List<Client> clients=null;
		 	 if(name.equals("1")){
	        //填充projects数据
		 		clients=clientService.findAllyifenPersonalgenzong();
	        if(clients.size()>0){
				for (Client client : clients) {
					Staff staff=staffSerivce.findById(client.getClient_staffId());
					if(staff!=null){
					client.setNewstaffName(staff.getStaff_name());
					}
				}
			}
		 	}else if(name.equals("2")){
		 		 //填充projects数据
		 		clients=clientService.findAllyifenPersonal();
	        if(clients.size()>0){
				for (Client client : clients) {
					Staff staff=staffSerivce.findById(client.getClient_staffId());
					if(staff!=null){
					client.setNewstaffName(staff.getStaff_name());
					}
				}
		 	}
		 	}
	        List<Map<String,Object>> list=createExcelRecord(clients,name);
	        String columnNames[]={"编号","客户姓名","联系QQ","电话","跟踪员工","来源渠道","追踪情况"};//列名
	        String keys[]   =    {"client_id","client_name","client_qq","client_phone","newstaffName","client_record","client_remarks"};//map中的key
	        ByteArrayOutputStream os = new ByteArrayOutputStream();
	        try {
	            DaoChuExcel.createWorkBook(list,keys,columnNames).write(os);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        byte[] content = os.toByteArray();
	        InputStream is = new ByteArrayInputStream(content);
	        // 设置response参数，可以打开下载页面
	        ServletOutputStream out = null;
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
				try {
					response.reset();
					response.setContentType("application/vnd.ms-excel;charset=utf-8");
					response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
					out = response.getOutputStream();
					bis = new BufferedInputStream(is);
					bos = new BufferedOutputStream(out);
					byte[] buff = new byte[2048];
					int bytesRead;
					// Simple read/write loop.
					while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					    bos.write(buff, 0, bytesRead);
					}
					if (bis != null)
					    bis.close();
					if (bos != null)
					    bos.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

	        return null;
    	}
	    private List<Map<String, Object>> createExcelRecord(List<Client> client2,String name) {
	        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("sheetName", "sheet1");
	        listmap.add(map);
	        if(name.equals("0")){
	        for (int j = 0; j < client2.size(); j++) {
	            Map<String, Object> mapValue = new HashMap<String, Object>();
	            mapValue.put("client_id", client2.get(j).getClient_id());
	            mapValue.put("client_name", client2.get(j).getClient_name());
	            mapValue.put("client_qq", client2.get(j).getClient_qq());
	            mapValue.put("client_phone", client2.get(j).getClient_phone());
	            mapValue.put("client_record", client2.get(j).getClient_record());
	            mapValue.put("client_remarks", client2.get(j).getClient_remarks());
	            listmap.add(mapValue);
	        }
	        }
	        if(name.equals("1") || name.equals("2")){
		        for (int j = 0; j < client2.size(); j++) {
		            Map<String, Object> mapValue = new HashMap<String, Object>();
		            mapValue.put("client_id", client2.get(j).getClient_id());
		            mapValue.put("client_name", client2.get(j).getClient_name());
		            mapValue.put("client_qq", client2.get(j).getClient_qq());
		            mapValue.put("client_phone", client2.get(j).getClient_phone());
		            mapValue.put("newstaffName", client2.get(j).getNewstaffName());
		            mapValue.put("client_record", client2.get(j).getClient_record());
		            mapValue.put("client_remarks", client2.get(j).getClient_remarks());
		            listmap.add(mapValue);
	        }
	        }
	        return listmap;
	    }
	    
	    private List<Map<String, Object>> dailiExcelRecord(List<Client> client2,String name) {
	        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("sheetName", "sheet1");
	        listmap.add(map);
	        for (int j = 0; j < client2.size(); j++) {
	            Map<String, Object> mapValue = new HashMap<String, Object>();
	            mapValue.put("client_id", client2.get(j).getClient_id());
	            mapValue.put("company_fuzeren", client2.get(j).getCompany_fuzeren());
	            mapValue.put("client_phone", client2.get(j).getClient_phone());
	            mapValue.put("client_qq", client2.get(j).getClient_qq());
	            mapValue.put("company_name", client2.get(j).getCompany_name());
	            if(client2.get(j).getClient_staffId() != null)
	            mapValue.put("newstaffName", staffSerivce.findById(client2.get(j).getClient_staffId()).getStaff_name());
	            mapValue.put("client_record", client2.get(j).getClient_record());
	            mapValue.put("client_remarks", client2.get(j).getClient_remarks());
	            listmap.add(mapValue);
	        }
	        return listmap;
	    }
	    /**
		 * 新用户开发前台正在跟踪客户和已开发客户入口
		 * @param staff
		 * @param file
		 * @return
		 */
		@RequestMapping("/qiangenzongcount")
		 public ModelAndView qiangenzongcount(PageUtil page,HttpServletResponse response,HttpServletRequest request,String select,String zhuizong){
			ModelAndView modelAndView=new ModelAndView();
			String idString = (String) request.getSession().getAttribute("staffs");
			String[] id = idString.split(","); 
			page.setPageSize(10);
			if(zhuizong.equals("0")){
				if(StringUtils.isBlank(select)){
					Integer count = clientService.findByStaffIdNumber(id);
					page.setRowCount(count);
				}else{
					Integer count = clientService.findByStaffIdAndSelectgengzongzongshu(id,select);
					page.setRowCount(count);
				}
			modelAndView.addObject("PageCount", page.getPageCount());
			modelAndView.addObject("PageNum", page.getPageNum());
			modelAndView.addObject("select", select);
			modelAndView.setViewName("forward:../client/html/gerenkehu.jsp");
			}
			if(zhuizong.equals("1")){
				if(StringUtils.isBlank(select)){
					Integer count = clientService.findByStaffIdNumberkaifa(id);
					page.setRowCount(count);
				}else{
					Integer count = clientService.findByStaffIdAndSelectyikaifazongshu(id,select);
					page.setRowCount(count);
				}
			modelAndView.addObject("PageCount", page.getPageCount());
			modelAndView.addObject("PageNum", page.getPageNum());
			modelAndView.addObject("select", select);
			modelAndView.setViewName("forward:../client/html/yonghuyikaifa.jsp");
			}
			//显示新增时下拉框里的名字选项
			List<Rank> ranks = rankService.listAll();
	    	modelAndView.addObject("ranks", ranks);
	    	List<Department> departments = departmentSerivce.findByAll();
	    	List<Staff> staffs = staffSerivce.findByAll();
	    	modelAndView.addObject("departments", departments);
	    	modelAndView.addObject("staffList", staffs);
			return modelAndView;
		}
		
		/**
		 * 前台用户开发员工正在跟踪客户显示
		 * 
		 * @param 
		 */
		@RequestMapping("/findByqiangenzong")
		public void findByqiangenzong(PageUtil page,String statu,String select,HttpServletResponse response,HttpServletRequest request){
			String idString = (String) request.getSession().getAttribute("staffs");
			String[] id = idString.split(","); 
			List<Client> clients = new ArrayList<>();
			page.setPageSize(10);
			if(!"".equals(select) && select!=null){
				Integer count = clientService.findByStaffIdAndSelectgengzongzongshu(id,select);
				
				if(count != null){
					page.setRowCount(count);	
				clients = clientService.findByStaffIdAndSelect(id,select,page.getEndIndex(),page.getBeginIndex());
				response.setContentType("text/json; charset=UTF-8");
				InteractiveUtil.WriteJsonForPage(clients, page, response);
				}	
			}else{
				Integer count = clientService.findByStaffIdNumber(id);
				
				if(count != null){
					page.setRowCount(count);
					//根据员工ID来查找销售机会
				clients = clientService.findByStaffIdqiangenzong(id,page.getEndIndex(),page.getBeginIndex());
				response.setContentType("text/json; charset=UTF-8");
				InteractiveUtil.WriteJsonForPage(clients, page, response);
				}
			}	
		}
		
		/**
		 * 前台用户开发员工已开发客户显示
		 * 
		 * @param 
		 */
		@RequestMapping("/findByqiankaifa")
		public void findByqiankaifa(PageUtil page,String statu,String select,HttpServletResponse response,HttpServletRequest request){
			String idString = (String) request.getSession().getAttribute("staffs");
			String[] id = idString.split(","); 
			List<Client> clients = new ArrayList<>();
			page.setPageSize(10);
			if(!"".equals(select) && select!=null){
				Integer count = clientService.findByStaffIdAndSelectyikaifazongshu(id,select);
				if(count != null){
				page.setRowCount(count);
				clients = clientService.findByStaffIdAndSelectkaifa(id,select,page.getEndIndex(),page.getBeginIndex());
				response.setContentType("text/json; charset=UTF-8");
				InteractiveUtil.WriteJsonForPage(clients, page, response);
				}	
			}else{
				Integer count = clientService.findByStaffIdNumber(id);
				if(count != null){
					page.setRowCount(count);
					//根据员工ID来查找销售机会
					clients = clientService.findByStaffIdkaifa(id,page.getEndIndex(),page.getBeginIndex());
				response.setContentType("text/json; charset=UTF-8");
				InteractiveUtil.WriteJsonForPage(clients, page, response);
				}
			}	
		}
		/**
		 * 新前台用户开发修改方法
		 * @param client
		 * @param request
		 * @param response
		 */
		@RequestMapping(value="update")
		public void update(Client client,HttpServletRequest request,HttpServletResponse response){
			if(client.getClient_id() != null){
					boolean b = clientService.update(client);
					if(b){
						InteractiveUtil.WriteStringForHtml("修改成功", response);
					}else{
						InteractiveUtil.WriteStringForHtml("修改失败", response);
					}
			}else{
				InteractiveUtil.WriteStringForHtml("该数据不存在，请刷新页面重试", response);
			}
			
		}
}
